package a12_图论;

import java.util.Scanner;
import java.util.Stack;

/**
 * <p>
 * a07_岛屿的最大面积复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/3/27
 */
public class a07_岛屿的最大面积复习1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int rows = scanner.nextInt();
        int cols = scanner.nextInt();

        int[][] gird = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                gird[i][j] = scanner.nextInt();
            }
        }

        int maxArea = 0;
        boolean[][] visited = new boolean[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(gird[i][j] == 1 && !visited[i][j]){//没有访问过的岛屿
                    area = 0;

                    visited[i][j] = true;
//                    dfs(gird,visited,i,j);
                    bfs(gird,visited,i,j);
                    //计算面积
                    maxArea = Math.max(maxArea, area + 1);
                }
            }
        }
        System.out.println(maxArea);
    }

    private static int area = 0;
    public static final int[][] dirs = new int[][]{{0,1},{1,0},{-1,0},{0,-1}};

    private static void dfs(int[][] gird, boolean[][] visited, int x, int y) {
        for (int[] dir : dirs) {
            int nextX = x + dir[0];
            int nextY = y + dir[1];
            if(nextX >= 0 && nextX < gird.length && nextY >= 0 && nextY < gird[0].length){
                if(gird[nextX][nextY] == 1 && !visited[nextX][nextY]){
                    visited[nextX][nextY] = true;
                    area++;
                    dfs(gird, visited, nextX, nextY);
                }
            }
        }
    }

    private static void bfs(int[][] gird, boolean[][] visited, int x, int y) {
        Stack<int[]> stack = new Stack<>();
        stack.add(new int[]{x,y});

        while (!stack.isEmpty()) {
            int[] pop = stack.pop();
            for (int[] dir : dirs) {
                int nextX = pop[0] + dir[0];
                int nextY = pop[1] + dir[1];
                if(nextX >= 0 && nextX < gird.length && nextY >= 0 && nextY < gird[0].length){
                    if(gird[nextX][nextY] == 1 && !visited[nextX][nextY]){
                        area++;
                        visited[nextX][nextY] = true;
                        stack.add(new int[]{nextX,nextY});
                    }
                }
            }
        }
    }

}
